import pygame


class BaseSprite(pygame.sprite.Sprite):
    def __init__(self, filename, speed=1):
        super().__init__()
        self.image = pygame.image.load(filename)
        self.rect = self.image.get_rect()
        self.speed = speed

    def update(self, *args):
        self.rect.y +=self.speed


class BgSprite(BaseSprite):
    """背景图片类"""
    def __init__(self, is_pre=False):
        super().__init__('./images/background.png', 5)
        if is_pre:
            self.rect.y = -700

    def update(self, *args):
        super().update()
        if self.rect.y>=700:
            self.rect.y=-700


class PlaneSprite(BaseSprite):
    """我方飞机类"""
    def __init__(self):
        super().__init__('./images/me1.png')
        self.rect.centerx = 240
        self.rect.y = 550


class PlaneGame:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((480, 700))
        pygame.display.set_caption('飞机大战')
        self.clock = pygame.time.Clock()
        self.is_loop = True
        self.create_sprites()


    def start(self):
        while self.is_loop:
            self.__event_handler()
            self.screen.fill((0,0,0))
            self.update_sprites()
            self.clock.tick(40)
            pygame.display.update()
        pygame.quit()

    def __event_handler(self):
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                self.is_loop = False

    def create_sprites(self):
        bg1 = BgSprite()
        bg2 = BgSprite(is_pre=True)
        self.bg_group = pygame.sprite.Group(bg1, bg2)
        self.plane = PlaneSprite()
        self.plane_group = pygame.sprite.Group(self.plane)

    def update_sprites(self):
        self.bg_group.update()
        self.bg_group.draw(self.screen)
        self.plane_group.draw(self.screen)

pg = PlaneGame()
pg.start()

